
#include "messagepacket.h"

//Returns Packet type identifier.
int MessagePacket::getPacketId() {
    return Packet::MessagePacketID;
}

//Returns size of the Package body in bytes.
int MessagePacket::getBodySize() {
    int result;
    QByteArray *temp = new QByteArray();
    QDataStream *stream = new QDataStream(temp, QIODevice::WriteOnly);
    if ((this->sendersNick == NULL) || (this->message == NULL))
        qFatal("Tried to send a message without initialize.");
    (*stream) << *(this->sendersNick) << *(this->message);
    result = temp->size();
    delete temp;
    delete stream;
    return result;
}

//Encodes the information of the packet in a QByteArray of getBodySize() bytes.
QByteArray MessagePacket::getBody() {
    QByteArray *temp = new QByteArray();
    QDataStream *stream = new QDataStream(temp, QIODevice::WriteOnly);
    if ((this->sendersNick == NULL) || (this->message == NULL))
        qFatal("Tried to send a message without initialize.");
    (*stream) << *(this->sendersNick) << *(this->message);
    QByteArray result(*temp);
    delete temp;
    delete stream;
    return result;
}

void MessagePacket::setFromBuffer(QByteArray *buffer) {
    QDataStream *stream = new QDataStream((const QByteArray) *buffer);
    QString nick;
    QString message;
    (*stream) >> nick >> message;
    this->sendersNick = new QString::QString(nick);
    this->message = new QString::QString(message);
    delete stream;
}

void MessagePacket::setNick(QString *nick) {
    if (this->sendersNick != NULL) delete this->sendersNick;
    this->sendersNick = new QString::QString(*nick);
}

void MessagePacket::setMessage(QString *msg) {
    if (this->message != NULL) delete this->message;
    this->message = new QString::QString(*msg);
}

QString MessagePacket::getNick() {
    QString *temp;
    if (this->sendersNick == NULL) temp = new QString::QString();
    else temp = new QString::QString(*(this->sendersNick));
    QString ret(*temp);
    delete temp;
    return ret;
}

QString MessagePacket::getMessage() {
    QString *temp;
    if (this->message == NULL) temp = new QString::QString();
    else temp = new QString::QString(*(this->message));
    QString ret(*temp);
    delete temp;
    return ret;
}

MessagePacket::MessagePacket() {
    this->message = NULL;
    this->sendersNick = NULL;
}

MessagePacket::~MessagePacket() {
    if (this->sendersNick != NULL) delete this->sendersNick;
    if (this->message != NULL) delete this->message;
}

